layui.use(['form', 'admin', 'ax', 'table', 'treetable', 'laytpl', 'element'], function () {
    var $ax = layui.ax;
    var admin = layui.admin;
    var table = layui.table;
    var treetable = layui.treetable;
    var form = layui.form;
    var laytpl = layui.laytpl;
    var element = layui.element;

    var Current = {
        tableId: "table"
    };

    Current.search = function () {
        var queryData = {
            appKey: $('#appId').val(),
        };
        table.reload(Current.tableId, {where: queryData});
    };

    Current.initColumn = function () {
        return [[
            {type: 'numbers'},
            {field: 'id', hide: true, sort: true, title: 'id'},
            {field: 'appKey', sort: false, title: 'AppKey'},
            {
                field: 'appKey', sort: false, title: '密钥', templet: function (d) {
                    return '<span style="color: #1E9FFF;cursor: pointer;" onclick="onShow(\'' + d.appKey + '\')">查看</span>';
                }
            },
            {
                field: 'roleList', sort: false, title: '角色', templet: function (d) {
                    var roles = d.roleList;
                    var arr = [];
                    for (var i = 0; i < roles.length; i++) {
                        arr.push(roles[i].description);
                    }
                    return arr.join(",")
                }
            },
            {
                field: 'secretKey', sort: false, title: '注册用户', templet: function (d) {

                    return d.userId === 0 ? '<span>否</span>' : '<span style="font-weight: bold;">是</span>';

                }
            },
            {field: 'status', sort: false, title: '状态', toolbar: '#statusTpl'},
            {field: 'gmtCreate', sort: false, title: '创建时间'},
            {field: 'remark', sort: false, title: '备注'},
            {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 215}
        ]];
    };

    Current.onEdit = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '编辑',
            area: ['60%', '70%'],
            content: system.contextPath + '/admin/isv/edit?id=' + data.id,
            end: function () {
                admin.getTempData('formOk') && table.reload(Current.tableId)
            }
        });
    };

    Current.onAdd = function (data) {
        admin.putTempData('formOk', false);
        top.layui.admin.open({
            type: 2,
            title: '添加',
            area: ['60%', '70%'],
            content: system.contextPath + '/admin/isv/add',
            end: function () {
                admin.getTempData('formOk') && table.reload(Current.tableId)
            }
        });
    };

    window.onShow = function (appId) {
        //查询应用详情
        //展示应用详情信息
        var part0Data = [];
        var ajax = new $ax(system.contextPath + "/api/isv.keys.get");
        ajax.setType("get");
        ajax.set({'appKey': appId})
        var result = ajax.start();
        if (result.status) {
            var data = result.data;
            part0Data.push(data);
        }

        var data0 = {
            list: part0Data,
        };
        var part0Temp = document.getElementById('part0-template');
        laytpl(part0Temp.innerHTML).render(data0, function (html) {
            //视频打开
            layer.open({
                area: '60%',
                title: '',
                content: html,
                yes: function (index, layero) {
                    //do something
                    layer.close(index);
                }
            });
        });
    }

    var keyFormat = 0;
    form.on('radio(keyFormat)', function (data) {
        keyFormat = data.value;
    });

    Current.managerKey = function (data) {
        //查询应用详情
        //展示应用详情信息
        var part0Data = [];
        var ajax = new $ax(system.contextPath + "/api/isv.keys.get");
        ajax.setType("get");
        ajax.set({'appKey': data.appKey})
        var result = ajax.start();
        if (result.status) {
            var data = result.data;
            keyFormat = result.data.keyFormat;
            part0Data.push(data);
        }

        var data0 = {
            list: part0Data,
        };
        var part0Temp = document.getElementById('part1-template');
        laytpl(part0Temp.innerHTML).render(data0, function (html) {
            //视频打开
            layer.open({
                btn: ['保存', '取消'],
                area: '60%',
                title: '密钥管理',
                content: html,
                yes: function (index, layero) {
                    //do something
                    var d = {};
                    var t = $('#dataForm').serializeArray();
                    $.each(t, function () {
                        d[this.name] = this.value;
                    });

                    var ajax = new $ax(system.contextPath + "/api/isv.keys.update", function (res) {
                        if (res.status) {
                            system.success("操作成功！");
                            layer.close(index);
                        } else {
                            system.error("失败：" + res.msg);
                        }
                    }, function (res) {
                        system.error("失败：" + res.msg);
                    });
                    ajax.set(d);
                    ajax.start();
                },
                btn2: function (index, layero) {
                    layer.close(index);
                }
            });

            form.render();
        });
    }
    var dataIndex = 0;
    //一些事件触发
    element.on('tab(demo)', function (data) {
        dataIndex = data.index;
    });

    /**
     * 重新生成秘钥
     */
    window.reloadKey = function () {
        var ajax = new $ax(system.contextPath + "/api/isv.keys.gen", function (res) {
            if (res.status) {
                system.success("操作成功！");
                if (dataIndex === 0) {
                    $('#publicKeyIsv').val(res.data.publicKey);
                    $('#privateKeyIsv').val(res.data.privateKey);
                } else {
                    $('#publicKeyPlatform').val(res.data.publicKey);
                    $('#privateKeyPlatform').val(res.data.privateKey);
                }
            } else {
                system.error("失败：" + res.msg);
            }
        }, function (res) {
            system.error("失败：" + res.msg);
        });
        ajax.set({keyFormat: keyFormat});
        ajax.start();
    }

    /**
     * 导出秘钥
     * @param data
     */
    Current.downloadKey = function (data) {
        var ajax = new $ax(system.contextPath + "/api/isv.keys.get");
        ajax.setType("get");
        ajax.set({'appKey': data.appKey})
        var result = ajax.start();
        if (result.status) {
            var appKey = result.data.appKey;
            const privateKeyIsv = result.data.privateKeyIsv
            const publicKeyPlatform = result.data.publicKeyPlatform
            let content = `AppId：` + appKey + `\n\n开发者私钥：\n` + privateKeyIsv + `\n\n` + `平台公钥：\n` + publicKeyPlatform
            var pom = document.createElement('a');
            pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(content));
            pom.setAttribute('download', appKey + `.txt`);
            if (document.createEvent) {
                var event = document.createEvent('MouseEvents');
                event.initEvent('click', true, true);
                pom.dispatchEvent(event);
            } else {
                pom.click();
            }
        }
    }

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Current.tableId,
        url: system.contextPath + '/api/isv.info.page',
        page: true,
        request: {
            pageName: 'pageIndex' //页码的参数名称，默认：page
            , limitName: 'pageSize' //每页数据量的参数名，默认：limit
        },
        height: "full-158",
        cellMinWidth: 100,
        cols: Current.initColumn(),
        parseData: function (res) { //res 即为原始返回的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.data.total, //解析数据长度
                "data": res.data.records //解析数据列表
            };
        }
        , response: {
            statusCode: 200
        }
        , size: 'lg',
        done: function (res, curr, count) {
            count || this.elem.next('.layui-table-view').find('.layui-table-header').css('overflow', 'visible');
            $('.layui-table-body').find('div.layui-table-cell').find('select').each(function () {
                var $this = $(this);
                var val = $this.data('value');
                var text;
                $(this).children().each(function () {
                    if (val == this.value) {
                        text = this.text;
                        return;
                    }
                })
                //更新layui 选择器输入框的值
                $this.next().find('.layui-select-title').find('input').val(text);
                //更新layui 选择器的值 以及设置其样式
                $this.val(val).parents('div.layui-table-cell').css('overflow', 'visible');
            })
            form.render(null, 'table');
        }
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Current.onAdd();
    });

    //搜索按钮点击事件
    $('#btnSearch').click(function () {
        Current.search();
    });


    // 监听修改update到表格中
    form.on('select(statusFilter)', function (data) {
        var id = $(data.elem).attr("data-id");
        var status = data.value;
        var param = {
            id: id,
            status: status,
        }
        updateBatchById(param)
    });

    function updateBatchById(data) {
        var ajax = new $ax(system.contextPath + "/api/isv.info.updateStatus", function (res) {
            if (res.status) {
                system.success("修改成功！");
                //重新加载表格
                table.reload(Current.tableId)
            } else {
                system.error("失败：" + res.msg);
            }
        }, function (res) {
            system.error("失败：" + res.msg);
        });
        ajax.set(data);
        ajax.start();
    }

    // 工具条点击事件
    table.on('tool(' + Current.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Current.onEdit(data);
        } else if (layEvent === 'delete') {
            Current.onDelete(data);
        } else if (layEvent === 'add') {
            Current.onAdd(data);
        } else if (layEvent === 'managerKey') {
            Current.managerKey(data);
        } else if (layEvent === 'downloadKey') {
            Current.downloadKey(data);
        }
    });
});
